import logging

import uvicorn
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

from src.config import ApiConfig, Settings

from .controllers import setup_controllers
from .middlewares import setup_middlewares
from .providers import setup_providers

logger = logging.getLogger(__name__)


def init_api(
    config: Settings,
) -> FastAPI:
    logger.debug("Initialize API")
    app = FastAPI(
        debug=config.api.debug,
        title="Atox Login",
        version="1.0.0",
        default_response_class=ORJSONResponse,
    )
    setup_middlewares(app, config)
    setup_providers(app, config)
    setup_controllers(app)

    return app


async def run_api(app: FastAPI, api_config: ApiConfig) -> None:
    config = uvicorn.Config(
        app,
        host=api_config.host,
        port=api_config.port,
        log_level=logging.INFO,
        log_config=None,
    )
    server = uvicorn.Server(config)
    logger.info("Running API")

    await server.serve()
